package com.njwb.day15.zqzb.jdbc03;

import com.njwb.day15.zqzb.util.DbUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Scanner;

public class UpdateStudent {
    public static void update() {
        Scanner input= new Scanner(System.in);
        System.out.println("请输入要修改的学生编号：");
        //提供要更新数据编号
        int sid= input.nextInt();

        Object[] objects = FindStudentById.execute(sid);

        if(objects==null) {
            System.out.println("没有此数据");
            return ;
        }
        System.out.println("找到了编号为6的数据："+ Arrays.toString(objects));
        //下面值是最终6号的数据
        System.out.println("请输入新的姓名");
        String name = input.next();
        System.out.println("请输入新的年龄");
        int age = input.nextInt();
        System.out.println("请输入新的地址");
        String address= input.next();
        //构建连接对象
        Connection connection= null ;
        //命令器
        PreparedStatement pstmt= null ;
        try {
            connection = DbUtil.getConnection();
            //3、创建命令器
            pstmt = connection.prepareStatement("update tb_student set sname= ? ,age=?,address=? where sid=?");
            //4、设置参数
            pstmt.setString(1,name);
            pstmt.setInt(2,age);
            pstmt.setString(3,address);
            pstmt.setInt(4,sid);

            //5.执行sql语句
            pstmt.executeUpdate();
            System.out.println("数据修改成功！！！");
        }  catch (SQLException e) {
            e.printStackTrace();
        }finally {
           DbUtil.closeConnection(null,pstmt,connection);
        }

    }
}
